//
//  DealerProxy.m
//  MultipleInheritanceDemo
//
//  Created by apple on 2018/1/4.
//  Copyright © 2018年 WJ. All rights reserved.
//

#import "DealerProxy.h"
#import <objc/runtime.h>

@interface DealerProxy(){
    BookProvider *_bookProvider;
    ClothesProvider *_clothesProvider;
    NSMutableDictionary *_methodsMap;
}
@end

@implementation DealerProxy
+ (instancetype)dealerProxy{
    return [[DealerProxy alloc] init];
}

- (instancetype)init{
    _methodsMap = [NSMutableDictionary dictionary];
    _bookProvider = [[BookProvider alloc] init];
    _clothesProvider = [[ClothesProvider alloc] init];
    
    [self registerMethodWithTarget:_bookProvider];
    [self registerMethodWithTarget:_clothesProvider];
    return self;
}

- (void)registerMethodWithTarget:(id)target{
    unsigned int number = 0;
    // 获取target方法列表
    Method *methodList = class_copyMethodList([target class], &number);
    for (int i = 0; i<number; i++) {
        Method method = methodList[i];
        SEL selector = method_getName(method);
        const char *methodName = sel_getName(selector);
        NSLog(@"%@",[NSString stringWithUTF8String:methodName]);
        [_methodsMap setObject:target forKey:[NSString stringWithUTF8String:methodName]];
    }
    free(methodList);
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
    NSString *methodName = NSStringFromSelector(sel);
    //在字典中查找对应的target
    id target = _methodsMap[methodName];
    if(target && [target respondsToSelector:sel]){
        return  [target methodSignatureForSelector:sel];
    }else{
        return [super methodSignatureForSelector:sel];
    }
}

- (void)forwardInvocation:(NSInvocation *)invocation{
    SEL sel = invocation.selector;
    NSString *methodName = NSStringFromSelector(sel);
    //在字典中查找对应的target
    id target = _methodsMap[methodName];
    if(target && [target respondsToSelector:sel]){
        [invocation invokeWithTarget:target];
    }else{
        [super forwardInvocation:invocation];
    }
}
@end
